<template>
  <div
    class="building-buckets"
    v-if="$store.getters.showBuildingCheck"
    @click="handleModalClose"
  >
    <div
      ref="drawerWrap"
      class="content-container"
      :style="{ left: containerLeft + 'px' }"
    >
      <section class="buckets-content" @click.stop>
        <section class="header">
          <div class="left">
            <building-icon iconType="org-louyuxiangmu"></building-icon>
            <div class="project-info">
              <div>
                {{ $store.getters.orgInfo.org_name || "项目集合" }}
                <a-tooltip>
                  <template #title>
                    企业有效期：{{
                      $store.getters.orgInfo.account.overdue_day
                    }}</template
                  >
                  <SafetyCertificateOutlined
                    v-if="$store.getters.basicConfig.can_reg_org"
                    style="color: green; margin-left: 5px"
                  />
                </a-tooltip>
              </div>
              <div class="desc">
                共计
                <cu-icon type="org-louyu"></cu-icon>
                <span class="ml-2">{{ buildingTotal }}</span>
              </div>
            </div>
          </div>
          <div class="right" v-if="villageTypeList.length">
            <a-select
              v-model:value="villageType"
              :options="villageTypeList"
              style="width: 120px"
              @select="handleVillageTypeChange"
            >
            </a-select>
          </div>
        </section>
        <section class="content">
          <a-row class="row" :gutter="16">
            <a-col :span="12" class="left">
              <a-row class="top box">
                <section class="title">
                  <span>
                    {{ $L("项目") }}
                    <a-popover trigger="click" title="搜索" :visible="villagePopVisible"  @visibleChange="(val) => changePopVisible(val, 'village')">
                    <template #content>
                      <a-input-search
                        v-model:value="villageSearchValue"
                        placeholder="请输入关键字搜索"
                        style="width: 200px"
                        enter-button
                        @search="onSearch('village')"
                      />
                    </template>
                    <SearchOutlined :class="villageSearchReal || villagePopVisible ? 'searching search-icon' : 'search-icon'"/>
                  </a-popover>
                  </span>
                </section>
                <section class="list-cont">
                  <template v-if="villageListHaveSearch.length">
                    <div
                      class="list-item"
                      v-for="item of villageListHaveSearch"
                      :key="item.id"
                      @click="handleVillageClick(item)"
                    >
                      <building-icon
                        :checked="item.checked"
                        :boxStyle="{ background: '#13c2c2' }"
                        iconType="org-louyuxiangmu"
                      ></building-icon>
                      <div class="info">
                        <div>
                          {{ item.name }}
                          <span
                            class="villageDelete"
                            @click.stop=""
                            v-if="item.buildList.length == 0"
                          >
                            <a-popconfirm
                              title="确认删除该项目吗?"
                              @confirm.stop="deleteVillageClick(item.id)"
                            >
                              <DeleteOutlined
                                v-permission="['villageList', 'curd', 'delete']"
                                style="color: red; margin-left: 10px"
                              />
                            </a-popconfirm>
                          </span>
                        </div>
                        <div class="desc">
                          <cu-icon type="org-louyu"></cu-icon>
                          <span class="ml-2">{{ item.buildList.length }}</span>
                        </div>
                      </div>
                      <a-button
                        type="link"
                        @click.stop="villageDetail(item.id)"
                      >
                        <template #icon>
                          <EyeOutlined />
                        </template>
                      </a-button>
                    </div>
                  </template>
                  <div v-else class="no-data">暂无项目</div>
                </section>
              </a-row>
              <a-row class="bottom box">
                <section class="title">
                  <span>{{ $L("楼宇集合") }}</span>
                  <a-button type="link" @click="bucketEdit()">
                    <template #icon>
                      <PlusOutlined />
                    </template>
                    新增
                  </a-button>
                </section>
                <section class="list-cont">
                  <template v-if="bucketList.length">
                    <div
                      class="list-item"
                      v-for="item of bucketList"
                      :key="item.id"
                      @click="handleBucketClick(item)"
                    >
                      <building-icon
                        :checked="item.checked"
                        :boxStyle="{ background: '#13c2c2' }"
                        iconType="org-louyujiqun"
                      ></building-icon>
                      <div class="info">
                        <div>{{ item.collection_name }}</div>
                        <div class="desc">
                          <cu-icon type="org-louyu"></cu-icon>
                          <span class="ml-2">{{
                            item.collection_build.length
                          }}</span>
                        </div>
                      </div>
                      <a-button type="link" @click.stop="bucketEdit(item.id)">
                        <template #icon>
                          <FormOutlined />
                        </template>
                      </a-button>
                    </div>
                  </template>
                  <div v-else class="no-data">暂无集合</div>
                </section>
              </a-row>
            </a-col>
            <a-col :span="12" class="right box">
              <section class="title">
                <span>
                  {{ $L("楼宇") }}
                  <a-popover trigger="click" title="搜索" :visible="buildPopVisible"  @visibleChange="(val) => changePopVisible(val, 'build')">
                    <template #content>
                      <a-input-search
                        v-model:value="buildSearchValue"
                        enter-button
                        placeholder="请输入关键字搜索"
                        style="width: 200px"
                        @search="onSearch('build')"
                      />
                    </template>
                    <SearchOutlined :class="buildSearchReal || buildPopVisible ? 'searching search-icon' : 'search-icon'" />
                  </a-popover>
                </span>
                <a-button type="link" @click="clearBuildingChecked">
                  <template #icon>
                    <ClearOutlined />
                  </template>
                  清空
                </a-button>
              </section>
              <section class="list-cont">
                <template v-if="buildListHaveSearch.length">
                  <div
                    class="list-item"
                    v-for="item of buildListHaveSearch"
                    :key="item.id"
                    @click="handleBuildingChecked(item)"
                  >
                    <building-icon
                      :checked="item.checked"
                      :boxStyle="{ background: '#f4b91e' }"
                      iconType="org-louyu"
                    ></building-icon>
                    <div class="info">
                      <div>{{ item.build_name || "--" }}</div>
                      <div class="village">{{ item.village_name }}</div>
                    </div>
                    <a-checkbox :checked="item.checked"></a-checkbox>
                  </div>
                </template>
                <div v-else class="no-data">暂无楼宇</div>
              </section>
            </a-col>
          </a-row>
        </section>
      </section>
    </div>
    <ProjectDetail
      :visible="villageDetailVisible"
      :id="villageId"
      :showDel="false"
      @cancel="handleVillageDetailClose"
      @edit="handlePageChange"
    />
    <buckets-add
      :visible="bucketEditVisible"
      :id="bucketId"
      :villageType="villageType"
      @cancel="handleBucketEditCancel"
      @success="handleBucketEditSuccess"
    ></buckets-add>
  </div>
</template>

<script>
import { computed, defineComponent, reactive, toRefs, watch } from "vue";
import BuildingIcon from "./modules/BuildingIcon.vue";
import BucketsAdd from "./modules/BucketsAdd.vue";
import {
  PlusOutlined,
  ClearOutlined,
  FormOutlined,
  EyeOutlined,
  DeleteOutlined,
  SafetyCertificateOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import store from "../../../store";
import { message } from "ant-design-vue";
import defaultSetting from "../../../common/utils/defaultSetting";
import dict from "../../../common/utils/dict";
import { useRouter } from "vue-router";
import utils from "../../../common/utils/utils";
import ProjectDetail from "../../../views/village/ProjectManage/ProjectDetail.vue";

export default defineComponent({
  name: "BuildingBuckets",
  components: {
    SearchOutlined,
    BuildingIcon,
    ProjectDetail,
    BucketsAdd,
    PlusOutlined,
    ClearOutlined,
    FormOutlined,
    EyeOutlined,
    DeleteOutlined,
    SafetyCertificateOutlined,
  },
  setup(props, context) {
    const $router = useRouter();

    const state = reactive({
      allVillage: [], // 所有的项目
      allBuidling: [], // 所有的楼宇
      allBuckets: [], // 所有的集合
      villageList: [], // 展示出来的项目
      buildingList: [], // 展示的楼宇
      buildingTotal: 0, // 展示的楼宇的数量
      bucketList: [], // 展示的集合
      villageType: "", //当前选中的楼宇类型
      villageTypeList: [], //项目类型列表
      // 项目详情
      villageDetailVisible: false,
      villageId: 0,
      // 添加编辑集合
      bucketEditVisible: false,
      bucketId: 0,
      old: {
        villageList: [],
        bucketList: [],
      },
      villagePopVisible: false,
      buildPopVisible: false,
      villageSearchReal: '',
      buildSearchReal: '',
      villageSearchValue: '',
      buildSearchValue: '',
    });

    const buildingInfo = computed(() => store.getters.buildingInfo);

    const menuType = computed(() => store.getters.userInfo.pc_menu_type);
    const containerLeft = computed(() => {
      if (menuType.value == 2) {
        return store.getters.customSideMenu ? store.getters.collapsed ? 145 : 240 : defaultSetting.NORMAL_MENU_WIDTH;
      } else {
        return store.getters.collapsed
          ? defaultSetting.COL_WIDTH
          : defaultSetting.UNCOL_WIDTH;
      }
    });

    const villageListHaveSearch = computed(() => state.villageList.filter((v) => v.name?.toLowerCase()?.indexOf(state.villageSearchReal.toLowerCase()) >= 0));

    const buildListHaveSearch = computed(() => state.buildingList.filter((v) => v.build_name?.toLowerCase()?.indexOf(state.buildSearchReal.toLowerCase()) >= 0));

    let existTypeList = [];
    let villageTypeChanged = false;

    // 切换项目类型
    const handleVillageTypeChange = () => {
      state.old.villageList = state.villageList;
      state.old.bucketList = state.bucketList;
      villageTypeChanged = true;
      getShowBuckets();
      getShowVillage();
    };

    // 项目选中
    const handleVillageClick = (village) => {
      resetChecked();
      if (!village.buildList || !village.buildList.length) {
        message.warning("该项目下没有楼宇，请为该项目添加楼宇后再进行选择哦~");
        return;
      }
      village.checked = !village.checked;
      setVillageBuildingChecked(village);
      getCheckedBuckets();
    };

    const setVillageBuildingChecked = (village) => {
      village.buildList.forEach((build) => {
        build.checked = village.checked;
      });
    };

    // 楼宇选中
    const handleBuildingChecked = (build, village, checked) => {
      resetChecked();
      if (village) {
        build.checked = checked;
      } else {
        build.checked = !build.checked;
        getCheckedBuckets();
      }
      setBuildingVillageChecked(build, village);
    };

    const setBuildingVillageChecked = (build, village) => {
      if (!village) {
        village = state.villageList.find((item) => item.id == build.village_id);
      }
      if (build.checked) {
        const index = village.buildList.findIndex((item) => !item.checked);
        village.checked = index === -1;
      } else {
        village.checked = false;
      }
    };

    // 集合选中
    const handleBucketClick = (bucket) => {
      resetChecked();
      const { collection_build } = bucket;
      bucket.checked = !bucket.checked;
      let villageMap = {};
      collection_build.forEach((item) => {
        let village = villageMap[item.village_id];
        if (!village) {
          village = villageMap[item.village_id] = state.villageList.find(
            (v) => v.id == item.village_id
          );
        }
        const build = village.buildList.find((b) => b.id == item.id);
        handleBuildingChecked(build, village, bucket.checked);
      });
    };

    // 切换项目类型后 之前的选中要重置
    const resetChecked = () => {
      if (villageTypeChanged) {
        state.old.villageList.forEach((village) => {
          village.checked = false;
          village.buildList.forEach((build) => {
            build.checked = false;
          });
        });
        state.old.bucketList.forEach((bucket) => {
          bucket.checked = false;
        });
        villageTypeChanged = false;
      }
    };

    const getVillage = () => {
      request
        .get("/org", "/build/villageAndBuildList", { show_by_type: 0 })
        .then((res) => {
          if (res.villageList.length) {
            state.allVillage = res.villageList;
            res.villageList.forEach((village) => {
              if (village.type && !existTypeList.includes(village.type)) {
                existTypeList.push(village.type);
              }
            });
            // 当前选中类型 优先选中有选择项的项目类型
            const { permissionBuildings } = buildingInfo.value;
            let village = null;
            if (permissionBuildings && permissionBuildings.length) {
              village = state.allVillage.find(
                (item) => item.id == permissionBuildings[0].id
              );
            }
            state.villageType = village ? village.type : existTypeList[0];
            getBuckets(() => {
              getShowVillage();
            });
            if (existTypeList.length > 1) {
              // 有多个项目类型时 显示项目类型选择下拉框
              getVillageTypes();
            }
          } else {
            state.allVillage = [];
            getShowVillage();
          }
        });
    };

    const resetSearch = () => {
      state.buildSearchValue = '';
      state.villageSearchValue = '';
      state.buildSearchReal = '';
      state.villageSearchReal = '';
    };

    const getShowVillage = () => {
      state.villageList = [];
      state.buildingList = [];
      resetSearch();
      if (state.allVillage.length) {
        state.allVillage.forEach((village) => {
          if (village.type == state.villageType) {
            state.villageList.push(village);
            state.buildingList = [...state.buildingList, ...village.buildList];
          }
        });
      }
      state.buildingTotal = state.buildingList.length;
      store.dispatch(
        "SetAllBuildings",
        JSON.parse(JSON.stringify(state.buildingList))
      );
      getCheckedVillageAndBuilding();
      getCheckedBuckets();
    };

    const getCheckedVillageAndBuilding = () => {
      const { permissionBuildings } = buildingInfo.value;
      state.villageList.forEach((village) => {
        const checkedVillage = permissionBuildings.find(
          (item) => item.id == village.id
        );
        if (checkedVillage) {
          village.checked =
            checkedVillage.build.length == village.buildList.length;
          village.buildList.forEach((build) => {
            build.checked = village.checked
              ? true
              : checkedVillage.build.includes(build.id);
          });
        }
      });
    };

    const getCheckedBuckets = () => {
      state.bucketList.forEach((bucket) => {
        bucket.checked = getCollectBuildChecked(bucket.collection_build);
      });
    };

    const getCollectBuildChecked = (buildList) => {
      let villageMap = {};
      for (let build of buildList) {
        let village = villageMap[build.village_id];
        if (!village) {
          villageMap[build.village_id] = village = state.villageList.find(
            (item) => item.id == build.village_id
          );
        }
        if (village) {
          const buildItem = village.buildList.find(
            (item) => item.id == build.id
          );
          if (!buildItem.checked) {
            return false;
          }
        } else {
          return false;
        }
      }
      return true;
    };

    const getVillageTypes = () => {
      request.get("/village", "/village/type/list").then((res) => {
        state.villageTypeList = [];
        res.list.forEach((item) => {
          if (existTypeList.includes(item.alias)) {
            state.villageTypeList.push({
              label: item.name,
              value: item.alias,
            });
          }
        });
      });
    };

    const getBuckets = (callback) => {
      request.get("/org", "/build/collection").then((res) => {
        state.allBuckets = res.list || [];
        getShowBuckets();
        callback && callback();
      });
    };

    const getShowBuckets = () => {
      state.bucketList = state.allBuckets.filter(
        (item) => item.village_type == state.villageType
      );
    };

    const init = () => {
      getVillage();
    };

    watch(
      () => store.getters.showBuildingCheck,
      (val) => {
        if (val) {
          init();
        } else {
          resetSearch();
        }
      }
    );

    //   关闭弹层 并保存
    const handleModalClose = () => {
      // 保存设置
      if (state.buildingList.length) {
        const params = getParams();
        if (params.buildId.length == 0) {
          message.warning("请至少选择一个楼宇哦~");
          return;
        }
        request
          .post("/org", "/user/specialSetting", {
            type: dict.BUILD_SET,
            content: JSON.stringify(params),
            needMsg: true,
          })
          .then((res) => {
            $router.go(0);
          });
      } else {
        store.dispatch("SetBuildingVisible", false);
        message.warning("请添加项目和楼宇~");
      }
    };

    const getParams = () => {
      let buildId = [];
      let villageId = [];
      let projectBuild = [];
      state.allVillage.forEach((village) => {
        if (village.type == state.villageType && village.buildList.length) {
          village.buildList.forEach((build) => {
            if (build.checked == true) {
              buildId.push(build.id);
              if (!villageId.includes(build.village_id)) {
                villageId.push(build.village_id);
                projectBuild.push({
                  id: build.village_id,
                  build: [build.id],
                  type: state.villageType,
                });
              } else {
                let project = projectBuild.find(
                  (item) => item.id == build.village_id
                );
                project.build.push(build.id);
              }
            }
          });
        }
      });
      return { buildId, villageId, projectBuild };
    };

    // 清空楼宇选中
    const clearBuildingChecked = () => {
      state.villageList.forEach((item) => {
        item.checked = false;
      });
      state.buildingList.forEach((item) => {
        item.checked = false;
      });
      state.bucketList.forEach((item) => {
        item.checked = false;
      });
    };

    // 添加编辑楼宇集合
    const bucketEdit = (id) => {
      state.bucketEditVisible = true;
      state.bucketId = id || 0;
    };
    const handleBucketEditCancel = () => {
      state.bucketEditVisible = false;
      state.bucketId = 0;
    };
    const handleBucketEditSuccess = () => {
      getBuckets(() => {
        getCheckedBuckets();
      });
      handleBucketEditCancel();
    };

    // 查看项目详情
    const villageDetail = (id) => {
      state.villageDetailVisible = true;
      state.villageId = id;
    };
    const handleVillageDetailClose = () => {
      state.villageDetailVisible = false;
      state.villageId = 0;
    };
    const handlePageChange = (detail) => {
      handleVillageDetailClose();
      handleBucketEditCancel();
      store.dispatch("SetBuildingVisible", false);
      $router.push({
        name: "projectEdit",
        query: { id: detail.id },
      });
    };

    // 删除项目
    const deleteVillageClick = (id) => {
      request.del("/village", "/project/manage", { id }).then((res) => {
        message.success("删除成功");
        getVillage();
      });
    };

    const onSearch = (type) => {
      if (type == 'village') {
        state.villageSearchReal = state.villageSearchValue;
        state.villagePopVisible = false;
        return;
      }
      if (type == 'build') {
        state.buildSearchReal = state.buildSearchValue;
        state.buildPopVisible = false;
        return;
      }
    };

    const changePopVisible = (val, type) => {
      if (type == 'village') {
        state.villagePopVisible = val;
        if (!val) {
          state.villageSearchValue = state.villageSearchReal;
        }
        return;
      }
      if (type == 'build') {
        state.buildPopVisible = val;
        if (!val) {
          state.buildSearchValue = state.buildSearchReal;
        }
        return;
      }
    };

    return {
      containerLeft,
      villageListHaveSearch,
      buildListHaveSearch,
      ...toRefs(state),
      handleModalClose,
      handleBuildingChecked,
      handleVillageClick,
      clearBuildingChecked,
      villageDetail,
      handleVillageDetailClose,
      handlePageChange,
      bucketEdit,
      handleBucketEditCancel,
      handleBucketEditSuccess,
      handleBucketClick,
      handleVillageTypeChange,
      deleteVillageClick,
      onSearch,
      changePopVisible,
    };
  },
});
</script>

<style lang="less" scoped>
.building-buckets {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 999;
  .content-container {
    position: relative;
    right: 0;
    top: 0;
    bottom: 0;
    height: 100%;
    background: rgba(0, 0, 0, 0.2);
    .buckets-content {
      width: 800px;
      height: 100%;
      background: #f4f4f4;
      box-sizing: border-box;
      .header {
        width: 100%;
        background: #fff;
        display: flex;
        align-items: center;
        padding: 10px 20px;
        box-sizing: border-box;
        height: 60px;
        justify-content: space-between;
        .left {
          display: flex;
          align-items: center;
          .project-info {
            flex: 1;
            margin-left: 15px;
            line-height: 20px;
            font-size: 12px;
            font-weight: bold;
            .desc {
              font-weight: normal;
              color: #999;
            }
          }
        }
      }
      .content {
        padding: 10px 20px 10px 10px;
        height: calc(~"100% - 60px");
        width: 100%;
        box-sizing: border-box;
        .row {
          height: 100%;
        }
        .box {
          background: #fff;
          border-radius: 4px;
          position: relative;
          .title {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            box-sizing: border-box;
            height: 40px;
            padding: 0 10px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #f1f1f1;
            font-weight: bold;
            background: #fff;
            z-index: 10;
          }
          .list-cont {
            height: 100%;
            overflow-y: auto;
            padding-top: 40px;
            width: 100%;
            .list-item {
              width: 100%;
              height: 50px;
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin-top: 10px;
              padding: 0 15px;
              cursor: pointer;
              .info {
                margin-left: 10px;
                line-height: 20px;
                font-size: 14px;
                flex: 1;
                color: rgba(0, 0, 0, 1);
                .villageDelete {
                  display: none;
                }
                .desc {
                  display: flex;
                  align-items: center;
                  color: #999;
                  font-weight: normal;
                }
                .village {
                  color: rgba(0, 0, 0, 0.4);
                  font-size: 12px;
                }
              }
            }
            .list-item:hover {
              .villageDelete {
                display: inline-block;
              }
            }
          }
        }
        .left,
        .right {
          height: 100%;
        }
        .top {
          height: 49%;
        }
        .bottom {
          height: 50%;
          margin-top: 2%;
        }
      }
    }
  }
}
.search-icon {
  padding: 0 4px;
  font-size: 16px;
}
.searching {
  color: @primary-color;
}
</style>
